package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.repository.IDestinationTemplateRepository;
import cn.wolfcode.luowowo.search.service.IDestinationSearchService;
import cn.wolfcode.luowowo.search.template.DestinationTemplate;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.Iterator;
import java.util.Optional;

@Service
public class DestinationSearchServiceImpl implements IDestinationSearchService {
    @Autowired
    private IDestinationTemplateRepository dao;

    //根据name查询地区
    public DestinationTemplate queryDestByName(String name) {
        Iterable<DestinationTemplate> iterable = dao.search(QueryBuilders.termQuery("name", name));
        Iterator<DestinationTemplate> iterator = iterable.iterator();
        while (iterator.hasNext()){
            return iterator.next();
        }
        return null;
    }

    public DestinationTemplate get(Long id) {
        Optional<DestinationTemplate> optional = dao.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    public void save(DestinationTemplate tt) {
        dao.save(tt);
    }

    @Autowired
    private ElasticsearchTemplate template;
    @Autowired
    private TransportClient client;

    public void createIndex() {
        template.createIndex(DestinationTemplate.class);
        template.getMapping(DestinationTemplate.class);
    }
}
